<?php

namespace app\api\controller;

use app\admin\model\Config;
use app\admin\model\VipCard;
use app\api\model\CompanyOrderModel;
use app\api\model\CompanyPackageModel;
use app\api\model\CompanySpecModel;
use app\api\model\GoodsModel;
use app\api\model\GoodsOrderModel;
use app\api\model\HandlerModel;
use app\api\model\HandlerOrderModel;
use app\api\model\MemberBill;
use app\api\model\MemberModel;
use app\api\model\SpecialOrder;
use app\api\model\VipCardBill;
use app\api\model\VipModel;
use app\api\model\VipOrderModel;
use EasyWeChat\Factory;
use think\Db;
use think\Exception;
use think\facade\Log;

class PayCall extends Api
{

    protected $noNeedLogin = ["*"];

    protected $app;

    public function __construct()
    {
        $this->app = Factory::payment(config('wechat.wechat_pay'));

    }


    //专项服务回调
    public function specialCallback()
    {
        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            $order_id = $message['out_trade_no'];
            // 查询订单是否存在
            $order = SpecialOrder::where(['out_trade_no' => $order_id, 'status' => 0])->find();
            if (!$order) {
                return true; // 订单不存在，不处理
            }
            try {
                // 用户是否支付成功
                if ($message['return_code'] !== 'SUCCESS') {
                    // 支付失败
                    return $fail('支付失败，请稍后再通知我');
                } else {
                    Db::startTrans();
                    $order->status = 1;
                    $order->pay_time = time();
                    $order->transaction_id = $message['transaction_id'];
                    $order->save();
                    //执行分销
                    $this->retail($order['id'], $order['member_id'], $order['pay_amount'], 'spec');
                    Db::commit();
                    return true;
                }
            } catch (\Exception $e) {
                Db::rollback();
                Log::mylog('specialCallback', ['message' => $message, 'error' => $e->getMessage()]);
            }
        });

        $response->send();
    }


    public function retail($order_id, $member_id, $amount, $income_type)
    {
        $config = (new Config())->where(['id' => [16, 17, 18]])->column('value', 'name');
        //查询用户信息
        $member = (new MemberModel())->where(['id' => $member_id])->find();
        //查询推荐来源
        if ($member['source'] == 1) {
            //查询上级
            $top_member = (new MemberModel())->where(['id' => $member['pid']])->find();
            if ($top_member) {
                $amount = number_format($config['team_retail'] / 100 * $amount,2);
                $this->addMemberBill($top_member, $member_id, $order_id, $amount, 1, 2, $income_type);
                //添加总金额
                (new MemberModel())->where(['id' => $top_member['id']])->setInc('team_total_money', $amount);
            }
        } elseif ($member['source'] == 2) {
            //财税顾问分销
            //一级分销比例
            //查询上级
            $top_member = (new MemberModel())->where(['id' => $member['pid']])->find();
            $amount1 = $config['advise_retail_first'] / 100 * $amount;
            $this->addMemberBill($top_member, $member_id, $order_id, $amount1, 2, 1, $income_type);
            //添加金额
            (new MemberModel())->where(['id' => $top_member['id']])->setInc('advise_total_money', $amount1);


            //二级分销比例
            $first_member = (new MemberModel())->where(['id' => $member['ppid']])->find();
            if ($first_member) {
                $amount2 = $config['advise_retail_two'] / 100 * $amount;
                $this->addMemberBill($first_member, $member_id, $order_id, $amount2, 2, 1, $income_type);
                //添加金额
                (new MemberModel())->where(['id' => $first_member['id']])->setInc('advise_total_money', $amount2);
            }
        }

        return true;
    }


    /**
     * @param $member 用户信息
     * @param $order 订单信息
     * @param $amount 反佣金额
     * @param $type 1间接推荐 2直接推荐
     * @param $retail_type 1:财税顾问。2:团队分销
     * @return void
     */
    public function addMemberBill($top_member, $member_id, $order_id, $amount, $type, $retail_type, $income_type)
    {
        $model = (new MemberBill());
        $model->member_id = $top_member['id'];
        $model->retail_member_id = $member_id;
        $model->order_id = $order_id;
        $model->income = $amount;
        $model->type = $type;
        $model->retail_type = $retail_type;
        $model->before_amount = $top_member['team_total_money'];
        $model->after_amount = $top_member['team_total_money'] + $amount;
        $model->income_type = $income_type;

        if (!$model->save()) {
            throw new Exception('分佣记录添加失败');
        }

        return true;
    }


    //企业服务套餐回调
    public function packageCallback()
    {

        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            $order_id = $message['out_trade_no'];
            // 查询订单是否存在
            $order = CompanyOrderModel::where(['out_trade_no' => $order_id, 'status' => 0])->find();

            if (!$order) {
                return true; // 订单不存在，不处理
            }
            try {
                // 用户是否支付成功
                if ($message['return_code'] !== 'SUCCESS') {
                    // 支付失败
                    return $fail('支付失败，请稍后再通知我');
                } else {
                    Db::startTrans();
                    //查询规格
                    $spec = (new CompanySpecModel())->where(['id' => $order['spec_id']])->find();
                    $expire_time = $this->createDay($spec['type'], $spec['nums']);
                    $order->status = 1;
                    $order->expire_time = $expire_time;
                    $order->pay_time = time();
                    $order->transaction_id = $message['transaction_id'];
                    // 处理订单
                    $order->save();
                    $this->retail($order['id'], $order['member_id'], $order['pay_amount'], 'package');
                    Db::commit();
                    return true;

                }
            } catch (\Exception $e) {
                Db::rollback();
                // 记录日志
                Log::mylog('packageCallback', ['message' => $message, 'error' => $e->getMessage()]);
            }

        });

        $response->send();
    }


    //商品支付
    public function goodsCallback()
    {
        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            $order_id = $message['out_trade_no'];
            // 查询订单是否存在
            $order = GoodsOrderModel::where(['out_trade_no' => $order_id, 'status' => 0])->find();

            if (!$order) {
                return true; // 订单不存在，不处理
            }
            try {
                // 用户是否支付成功
                if ($message['return_code'] !== 'SUCCESS') {
                    // 支付失败
                    $order->status = 2;
                    $order->save();// 更新订单状态为支付失败
                    return $fail('支付失败，请稍后再通知我');
                } else {

                    Db::startTrans();
                    $order->status = 1;
                    $order->pay_time = time();
                    $order->transaction_id = $message['transaction_id'];
                    // 处理订单
                    $order->save();
                    //增加销量
                    (new GoodsModel())->where(['id' => $order['goods_id']])->setInc('sales');
                    $this->retail($order['id'], $order['member_id'], $order['pay_amount'], 'goods');

                    Db::commit();
                    return true;
                }
            } catch (\Exception $e) {
                Db::rollback();
                Log::mylog('goodsCallback', ['message' => $message, 'error' => $e->getMessage()]);
            }
            // 记录日志

        });

        $response->send();
    }


    public function handlerCallback()
    {
        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            $order_id = $message['out_trade_no'];
            // 查询订单是否存在
            $order = HandlerOrderModel::where(['out_trade_no' => $order_id, 'status' => 0])->find();

            if (!$order) {
                return true; // 订单不存在，不处理
            }
            try {
                // 用户是否支付成功
                if ($message['return_code'] !== 'SUCCESS') {
                    // 支付失败
                    return $fail('支付失败，请稍后再通知我');
                } else {

                    Db::startTrans();
                    $order->status = 1;
                    $order->pay_time = time();
                    $order->transaction_id = $message['transaction_id'];
                    // 处理订单
                    $order->save();
                    //查询财税信息
                    $handler = (new HandlerModel())->where(['id' => $order['handler_id']])->find();
                    (new MemberModel())->where(['id' => $order['member_id']])->update(['advise_level' => $handler['level']]);
                    (new MemberModel())->where(['id' => $order['member_id']])->setInc('bond', $order['price']);
                    $this->retail($order['id'], $order['member_id'], $order['price'], 'handler');

                    //添加保证金

                    Db::commit();
                    return true;
                }
            } catch (\Exception $e) {
                Db::rollback();
                Log::mylog('handlerCallback', ['message' => $message, 'error' => $e->getMessage()]);
            }

        });

        $response->send();
    }


    public function vipCallback()
    {
//        $message = array(
//        'appid' => 'wx78e3e718ce2d8bbc',
//        'bank_type' => 'OTHERS',
//        'cash_fee' => '1',
//        'fee_type' => 'CNY',
//        'is_subscribe' => 'N',
//        'mch_id' => '1673544995',
//        'nonce_str' => '663b77e2bc45a',
//        'openid' => 'otBIE7cP52UPhvRiYXo85TnIxgHY',
//        'out_trade_no' => 'VIP24082854544954',
//        'result_code' => 'SUCCESS',
//        'return_code' => 'SUCCESS',
//        'sign' => 'B2EE49B09C37EE0C8A920F5F58A26B54',
//        'time_end' => '20240508210238',
//        'total_fee' => '1',
//        'trade_type' => 'JSAPI',
//        'transaction_id' => '4200002207202405081359867395',
//        );



        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            $order_id = $message['out_trade_no'];
            // 查询订单是否存在
            $order = VipOrderModel::where(['out_trade_no' => $order_id, 'status' => 0])->find();

            if (!$order) {
                return true; // 订单不存在，不处理
            }
            try {
                // 用户是否支付成功
                if ($message['return_code'] !== 'SUCCESS') {
                    return $fail('支付失败，请稍后再通知我');
                } else {

                    Db::startTrans();
                    $order->status = 1;
                    $order->pay_time = time();
                    $order->transaction_id = $message['transaction_id'];

                    //获取vip信息
                    $vip = (new VipCard())->where(['id' => $order['vip_id']])->find();
                    //计算vip到期时间
                    $expire_time = $this->createDay($vip['expire_type'], $vip['nums']);
                    $order->vip_expire_time = $expire_time;
                    // 处理订单
                    $order->save();

                    //更新用户信息
                    (new MemberModel())->where(['id' => $order['member_id']])
                        ->update(['vip_type' => $vip['id'], 'vip_expire_time' => $expire_time]);
                    //分销
                    $this->retail($order['id'], $order['member_id'], $order['pay_amount'], 'vip');

                    //钱包增加金额
                    (new MemberModel())->where(['id' => $order['member_id']])->setInc('wallet',$order['pay_amount']);

                    //添加开通记录
                    (new VipCardBill())->addBill($order['member_id'], "购买" . $order['vip_name'], 1, $order['pay_amount']);


                    //添加保证金
                    Db::commit();
                    return true;
                }
            } catch (\Exception $e) {
                Db::rollback();
                Log::mylog('handlerCallback', ['message' => $message, 'error' => $e->getMessage()]);
            }

        });

        $response->send();
    }


    public function createDay($type, $num)
    {
        $start = date('Y-m-d H:i:s');
        switch ($type) {
            case 1:
                $date = date('Y-m-d H:i:s', strtotime($start . '+' . $num . ' month'));
                break;
            case 2:
                $date = date('Y-m-d H:i:s', strtotime($start . '+' . ($num * 3) . ' month'));
                break;
            case 3:
                $date = date('Y-m-d H:i:s', strtotime($start . '+' . $num . ' year'));
                break;
            case 4:
                $date = date('Y-m-d H:i:s', strtotime($start . '+' . 99 . ' year'));
                break;
        }
        return strtotime($date);
    }


}